import json

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from app.models import Comment, Article, Category, Tag


def index(request):
    p = request.GET.get("p", 1)
    context = {"p": p, "current": "index"}
    return render(request, "index.html", context)


def category(request, category_id):
    p = request.GET.get("p", 1)
    c = Category.objects.filter(id=category_id).first()

    context = {
        "c": c,
        "p": p,
        "current": category_id
    }
    return render(request, "category_list.html", context)


def tag(request, tag_id):
    p = request.GET.get("p", 1)
    t = Tag.objects.filter(id=tag_id).first()
    context = {
        "t": t,
        "p": p
    }
    return render(request, "tag_list.html", context)


def article(request, article_id):
    context = {"aid": article_id}
    return render(request, "article_detail.html", context)


def ajax_comment(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')

    article_id = request.POST.get("articleId")
    comment_content = request.POST.get("commentContent")
    comment_article = Article.objects.filter(id=article_id).first()

    comment = Comment(
        article=comment_article,
        content=comment_content,
        ip=ip,
        parent=None)
    comment.save()
    resp = {'code': 0, 'msg': 'success'}
    return HttpResponse(json.dumps(resp), content_type="application/json")


def about(request):
    return render(request, "about.html", {})
